//    Time Surfer
//    Copyright (C) 2008  Gaian Mystery School
//    http://www.gaianmysteryschool.com
//
//    This program is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    This program is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with this program.  If not, see <http://www.gnu.org/licenses/>

#import "TimeSurferController.h"
#import "TimeKit.h"
#import "Dreamspell.h"


// @@@ TODO fix end/begin date verify and hard coded dates
// switch to long count dates for premade dates.

static NSString *kAppName = @"Time Surfer";
static NSString *kBookmarkYear=@"Year";
static NSString *kBookmarkMonth=@"Month";
static NSString *kBookmarkDay=@"Day";
static NSString *kBookmarksKey=@"Bookmarks";
static NSString *kEndDateKey=@"End Date Key";
static NSString *kiCalImport=@"Would like to import into iCal now?";
static NSString *PACALDAY= @"Pacal Votan Auspicious Day";

@implementation TimeSurferController

int monthsMax[]={0,31,28,31,30,31,30,31,31,30,31,30,31}; 


- (IBAction)cleanQuit:(id)sender
{
	NSString *identifier=[[_tabControl selectedTabViewItem] identifier];
	
	if ([identifier compare: @"Notes"] == 0)
		[self saveNotes];

	[NSApp terminate:sender];
}

char *weekDay[]={"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"}; 

- (void)setDaySpinnerMax:(int)month
{
	int max = monthsMax[month];
	[_dayStepper setMaxValue: max];
}

- (void)goGregorianDate:(int)year month:(int)month day:(int)day
{
	NSCalendarDate *calDate = [NSCalendarDate dateWithYear:year month:month day:day hour:00 minute:00 second:00 timeZone:[NSTimeZone systemTimeZone]];
	[_gregorianMonth selectItemAtIndex:[calDate monthOfYear]-1];	
	[_gregorianDay setIntValue: [calDate dayOfMonth]];
	[_gregorianYear setIntValue: [calDate yearOfCommonEra]];
	
	[self setDaySpinnerMax: [calDate monthOfYear]];
	[self calcGregorian:self];
}

- (void)updateDayOfTheWeek
{
	NSCalendarDate *calDate = [NSCalendarDate dateWithYear:[_gregorianYear intValue] month:[[_gregorianMonth selectedItem] tag] day:[_gregorianDay intValue] hour:00 minute:00 second:00 timeZone:[NSTimeZone systemTimeZone]];
	[_dayOfTheWeek setStringValue: [NSString stringWithFormat: @"%s", weekDay[[calDate dayOfWeek]]]];
}

-(void)toneSealSearchDreamspell:(int)tone seal:(int)seal
{
	NSCalendarDate *calDate = [TimeKit endDate];

	int year,day, month;
	BOOL stop=0;
	
	day=[_gregorianDay intValue]+1;
	month=[[_gregorianMonth selectedItem] tag];
	
	for (year=[_gregorianYear intValue]; year<=[calDate yearOfCommonEra] && !stop; year++)
	{
		for (; month<13  && !stop; month++)
		{
			for (; day<monthsMax[month]  && !stop; day++)
			{
				Dreamspell *ds = [[Dreamspell alloc] initWithDate:month  day:day year:year];
				if ([ds tone]==tone && [ds seal]==seal)
				{
					[_gregorianDay setIntValue:day];
					[_gregorianYear setIntValue:year];
					[_gregorianMonth selectItemAtIndex: month-1];
					[_dayStepper setMaxValue: monthsMax[month]];
					[_yearStepper setIntValue: year];

					[self calcGregorian: self];
					stop=1;
				}
				[ds release];
			}
			day = 1;
		
		}
		month = 1;
	}
}


-(void)toneSealSearchLongCount:(int)tone seal:(int)seal
{
	NSCalendarDate *calDate = [TimeKit endDate];

	int year,day, month;
	BOOL stop=0;
	
	day=[_gregorianDay intValue]+1;
	month=[[_gregorianMonth selectedItem] tag];
	
	for (year=[_gregorianYear intValue]; year<=[calDate yearOfCommonEra] && !stop; year++)
	{
		for (; month<13  && !stop; month++)
		{
			for (; day<monthsMax[month]  && !stop; day++)
			{
				TimeKit *tk = [[TimeKit alloc] init];
				
				[tk initDays: [tk longCountFromDate:month day:day year:year]];
				if ([tk tzolkinDays]==tone && [tk tzolkinMonths]==seal)
				{
					[_gregorianDay setIntValue:day];
					[_gregorianYear setIntValue:year];
					[_gregorianMonth selectItemAtIndex: month-1];
					[_dayStepper setMaxValue: monthsMax[month]];
					[_yearStepper setIntValue: year];
					
					[self calcGregorian: self];
					stop=1;
				}
				[tk release];
			}
			day = 1;
			
		}
		month = 1;
	}
}


- (void)verifyBeginningDate
{
	NSCalendarDate *calDate = [TimeKit startDate];

	if ([_gregorianYear intValue]<=[calDate yearOfCommonEra])
	{
		[_gregorianYear setIntValue: [calDate yearOfCommonEra]];

		if ([[_gregorianMonth selectedItem] tag]<=[calDate monthOfYear])
		{
			[_gregorianMonth selectItemAtIndex:[calDate monthOfYear]-1];	
			[self setDaySpinnerMax: [calDate monthOfYear]];

			if ([_gregorianDay intValue]<[calDate dayOfMonth])
				[_gregorianDay setIntValue: [calDate dayOfMonth]];
		}
	}
}

- (void)verifyEndDate
{
	NSCalendarDate *calDate = [TimeKit endDate];

	if ([_gregorianYear intValue]>=[calDate yearOfCommonEra])
	{
		[_gregorianYear setIntValue: [calDate yearOfCommonEra]];

		if ([[_gregorianMonth selectedItem] tag]>=[calDate monthOfYear])
		{
			[_gregorianMonth selectItemAtIndex:[calDate monthOfYear]-1];	
			[self setDaySpinnerMax: [calDate monthOfYear]];

			if ([_gregorianDay intValue]>[calDate dayOfMonth])
				[_gregorianDay setIntValue: [calDate dayOfMonth]];
		}
	}
}


-(void)showCount:(TimeKit*)tk
{
	[_baktun setIntValue: [tk baktun]]; 
	[_katun setIntValue: [tk katun]]; 
	[_tun setIntValue: [tk tun]]; 
	[_uinal setIntValue: [tk uinal]]; 
	[_kin setIntValue: [tk kin]];
	
	NSString *name=[NSString stringWithFormat: @"tone%d", [tk tzolkinDays]];
	[_longCountTone setImage: [NSImage imageNamed: name]];
	
	int glyph = [tk tzolkinMonths]+1;
	if (glyph >=20) glyph-=20;
	name=[NSString stringWithFormat: @"glyph%d", glyph];
	[_longCountSign setImage: [NSImage imageNamed: name]];
	
	[_tzolkin setStringValue: [tk tzolkinSign]];
	[_haab setStringValue: [tk haabSign]];
	

	[_daysElapsed setStringValue: [NSString stringWithFormat: @"%d", [tk daysElapsed]]];
	[_daysRemaining setStringValue: [NSString stringWithFormat: @"%d", [tk daysRemaining]]];
	
	[_calendarRound longCount:[tk baktun] katun:[tk katun] tun:[tk tun] uinal:[tk uinal] kin:[tk kin]];
	[_calendarRound setNeedsDisplay: YES];
}

-(void)showDreamspell:(Dreamspell*)ds
{
	NSString *name=[NSString stringWithFormat: @"glyph%d", [ds destinyKin]];
	[_destinyKin setImage: [NSImage imageNamed: name ]];

	name=[NSString stringWithFormat: @"glyph%d", [ds guideKin]];
	[_guideKin setImage: [NSImage imageNamed: name ]];

	name=[NSString stringWithFormat: @"glyph%d", [ds analogKin]];
	[_analogKin setImage: [NSImage imageNamed: name ]];

	name=[NSString stringWithFormat: @"glyph%d", [ds antipodeKin]];
	[_antipodeKin setImage: [NSImage imageNamed: name ]];

	name=[NSString stringWithFormat: @"glyph%d", [ds occultKin]];
	[_occultKin setImage: [NSImage imageNamed: name ]];
	
	name=[NSString stringWithFormat: @"tone%d", [ds tone]];
	[_dreamspellTone setImage: [NSImage imageNamed: name]];


	[_guideLabel setStringValue: [ds guideKinLabel]];
	[_antipodeLabel setStringValue: [ds antipodeKinLabel]];
	[_analogLabel setStringValue: [ds analogKinLabel]];
	[_occultLabel setStringValue: [ds occultKinLabel]];
	[_dreamspell setStringValue: [ds dreamspellText]];
	[_moonDay setStringValue: [ds moonDay]];
	[_dreamspellGlyph  setStringValue: [ds dreamspellGlyph]];
	[_gap setStringValue: ([ds isGAP] ? @"Galactic Activation Portal" : @"")];
	[_dreamspellYear setStringValue: [ds dreamspellYearText]];
	
	[_pacalAuspiciousDay setStringValue: ([ds isPacalAuspiciousDay] ? PACALDAY : @"")];
}

-(void)awakeFromNib
{
	[self updateBookmarksMenu];
	[_yearStepper setMaxValue:[[TimeKit endDate] yearOfCommonEra]];
	[_yearStepper setMinValue:[[TimeKit startDate] yearOfCommonEra]];

	[_window center];
	[self today: self];
}

- (IBAction)changeMonth:(id)sender
{
	[self setDaySpinnerMax: [[_gregorianMonth selectedItem] tag] ];
}

- (IBAction)yearStepper:(id)sender
{
	[_gregorianYear setIntValue: [_yearStepper intValue]];
	[self calcGregorian:self];
}

- (IBAction)longCountStepper:(id)sender
{
	int stepper=[_longCountStepper intValue];
	NSCalendarDate *date=[TimeKit daysRemainingToNSCalendarDate: stepper];
	if ([date monthOfYear]==2 && [date dayOfMonth]==29)
	{
		if ([_gregorianDay intValue]==1)
			date=[TimeKit daysRemainingToNSCalendarDate: stepper-1];
		else
			date=[TimeKit daysRemainingToNSCalendarDate: stepper+1];
	}
	[_gregorianMonth selectItemAtIndex:[date monthOfYear]-1];	
	[_gregorianDay setIntValue: [date dayOfMonth]];
	[_gregorianYear setIntValue: [date yearOfCommonEra]];
	
	[self setDaySpinnerMax: [date monthOfYear]];
	[self calcGregorian:self];

}



- (IBAction)calc:(id)sender
{
	
	int baktun=[_baktun intValue];
	int katun=[_katun intValue];
	int tun=[_tun intValue];
	int uinal=[_uinal intValue];
	int kin=[_kin intValue];

	if (kin<0)
		kin=0;
	if (uinal<0)
		uinal=0;
	if (tun<0)
		tun=0;
	if (katun<0)
		katun=0;
	if (baktun<0)
		baktun=0;
		
	if (baktun>=13)
	{
		if (kin || uinal || tun || katun)
		{
			kin=0;
			uinal=0;
			tun=0;
			katun=0;
		}
		baktun=13;
	}
	
	[self gotoLongCount:baktun katun:katun tun:tun uinal:uinal kin:kin];
}

- (void)gotoLongCount:(int)baktun katun:(int)katun tun:(int)tun uinal:(int)uinal kin:(int)kin
{

	TimeKit *tk = [[TimeKit alloc] init];
	
	int longCount= [tk longCount:baktun katun:katun tun:tun uinal:uinal kin:kin];
	[tk initDays: longCount];
	[self showCount: tk];

	NSCalendarDate *date=[tk longCountToNSCalendarDate:baktun katun:katun tun:tun uinal:uinal kin:kin];
	
	[tk release];

	[_gregorianMonth selectItemAtIndex:[date monthOfYear]-1];	
	[_gregorianDay setIntValue: [date dayOfMonth]];
	[_gregorianYear setIntValue: [date yearOfCommonEra]];
	
	[self setDaySpinnerMax: [date monthOfYear]];
	[self calcGregorian:self];
	
}

- (IBAction)dayStepper:(id)sender
{   
	[_gregorianDay setIntValue: [_dayStepper intValue]];
	[self calcGregorian:self];

}

- (IBAction)calcGregorian:(id)sender
{
	[self verifyBeginningDate];
	[self verifyEndDate];
	
	if ([_gregorianDay intValue]==0)
		[_gregorianDay setIntValue:1];
	
	if ([_gregorianDay intValue]>monthsMax[[[_gregorianMonth selectedItem] tag]])
		[_gregorianDay setIntValue:monthsMax[[[_gregorianMonth selectedItem] tag]]];
	

	[self updateDayOfTheWeek];
	
	TimeKit *tk = [[TimeKit alloc] init];
	
	[tk initDays: [tk longCountFromDate:[[_gregorianMonth selectedItem] tag] day:[_gregorianDay intValue] year:[_gregorianYear intValue]]];
	[_longCountStepper setIntValue: [tk daysElapsed]];
	[self showCount: tk];
	[tk release];
	
	Dreamspell *ds = [[Dreamspell alloc] initWithDate:[[_gregorianMonth selectedItem] tag]  day:[_gregorianDay intValue] year:[_gregorianYear intValue]];
	[self showDreamspell: ds];
	[ds release];

	[_dayStepper setIntValue: [_gregorianDay intValue]];
	[_yearStepper setIntValue: [_gregorianYear intValue]];
	
	NSString *identifier=[[_tabControl selectedTabViewItem] identifier];
	
	if ([identifier compare: @"Notes"] == 0)
	{
		[self saveNotes];
		[self loadNotes];
	}

}

- (IBAction)search:(id)sender
{
	Dreamspell *ds = [[Dreamspell alloc] initWithDate:[[_gregorianMonth selectedItem] tag]  day:[_gregorianDay intValue] year:[_gregorianYear intValue]];
	[_searchTone selectItemAtIndex: [ds tone]-1];
	[_searchSeal selectItemAtIndex: [ds seal]];
	[ds release];


	[NSApp beginSheet: _searchPanel modalForWindow: _window modalDelegate: self didEndSelector: nil contextInfo: nil];

}

- (IBAction)searchOK:(id)sender
{
	[self toneSealSearchDreamspell:[[_searchTone  selectedItem] tag] seal:[[_searchSeal  selectedItem] tag]];

	[NSApp endSheet: _searchPanel];
	[_searchPanel orderOut: self];

}

- (IBAction)searchCancel:(id)sender
{
	[NSApp endSheet: _searchPanel];
	[_searchPanel orderOut: self];
}


- (IBAction)searchEnergies:(id)sender
{
	Dreamspell *ds = [[Dreamspell alloc] initWithDate:[[_gregorianMonth selectedItem] tag]  day:[_gregorianDay intValue] year:[_gregorianYear intValue]];
	[_searchEnergiesTone selectItemAtIndex: [ds tone]-1];
	[_searchEnergiesSeal selectItemAtIndex: [ds seal]];
	[ds release];

	[NSApp beginSheet: _searchEnergiesPanel modalForWindow: _window modalDelegate: self didEndSelector: nil contextInfo: nil];
}

- (IBAction)searchEnergiesPanelOK:(id)sender
{
	[self toneSealSearchDreamspell:[[_searchEnergiesTone  selectedItem] tag] seal:[[_searchEnergiesSeal  selectedItem] tag]];

	[NSApp endSheet: _searchEnergiesPanel];
	[_searchEnergiesPanel orderOut: self];

}

- (IBAction)searchEnergiesPanelCancel:(id)sender
{
	[NSApp endSheet: _searchEnergiesPanel];
	[_searchEnergiesPanel orderOut: self];
}

- (IBAction)next:(id)sender
{
	Dreamspell *ds = [[Dreamspell alloc] initWithDate:[[_gregorianMonth selectedItem] tag]  day:[_gregorianDay intValue] year:[_gregorianYear intValue]];
	[self toneSealSearchDreamspell:[ds tone] seal:[ds seal]];
	[ds release];
}

- (IBAction)searchLC:(id)sender
{
	TimeKit *tk = [[TimeKit alloc] init];
	
	[tk initDays: [tk longCountFromDate:[[_gregorianMonth selectedItem] tag] day:[_gregorianDay intValue] year:[_gregorianYear intValue]]];
	[_searchLCTone selectItemAtIndex: [tk tzolkinDays]-1];
	[_searchLCSeal selectItemAtIndex: [tk tzolkinMonths]];
	[tk release];
	
	[NSApp beginSheet: _searchLCPanel modalForWindow: _window modalDelegate: self didEndSelector: nil contextInfo: nil];
}

- (IBAction)searchLCPanelOK:(id)sender
{
	[self toneSealSearchLongCount:[[_searchLCTone  selectedItem] tag] seal:[[_searchLCSeal  selectedItem] tag]];
	
	[NSApp endSheet: _searchLCPanel];
	[_searchLCPanel orderOut: self];
	
}

- (IBAction)searchLCPanelCancel:(id)sender
{
	[NSApp endSheet: _searchLCPanel];
	[_searchLCPanel orderOut: self];
}

- (IBAction)nextLCMatch:(id)sender
{
	TimeKit *tk = [[TimeKit alloc] init];
	
	[tk initDays: [tk longCountFromDate:[[_gregorianMonth selectedItem] tag] day:[_gregorianDay intValue] year:[_gregorianYear intValue]]];
	[self toneSealSearchLongCount:[tk tzolkinDays] seal:[tk tzolkinMonths]];
	[tk release];
}

- (IBAction)today:(id)sender
{
	NSCalendarDate *calDate = [NSCalendarDate calendarDate];
	[_gregorianMonth selectItemAtIndex:[calDate monthOfYear]-1];	
	[_gregorianDay setIntValue: [calDate dayOfMonth]];
	[_gregorianYear setIntValue: [calDate yearOfCommonEra]];
	
	[self setDaySpinnerMax: [calDate monthOfYear]];
	[self calcGregorian:self];
}


- (IBAction)goHarmonic:(id)sender
{
	[self goGregorianDate:1987 month:8 day:16];
}

- (IBAction)goPacalBirth:(id)sender
{
	[self gotoLongCount:9 katun:8 tun:9 uinal:13 kin:0];
}

- (IBAction)goPacal1:(id)sender
{
	[self gotoLongCount:9 katun:13 tun:0 uinal:0 kin:0];
}

- (IBAction)goPacal2:(id)sender
{
	[self goGregorianDate:1952 month:6 day:15];
}

- (IBAction)goVenus1:(id)sender
{
	[self goGregorianDate:2004 month:6 day:8];
}

- (IBAction)goVenus2:(id)sender
{
	[self goGregorianDate:2012 month:6 day:6];
}

- (IBAction)go1Day:(id)sender
{
	[self goGregorianDate:1999 month:1 day:5];
}

- (IBAction)go1Night:(id)sender
{
	[self goGregorianDate:1999 month:12 day:31];
}

- (IBAction)go2Day:(id)sender
{
	[self goGregorianDate:2000 month:12 day:25];
}

- (IBAction)go2Night:(id)sender
{
	[self goGregorianDate:2001 month:12 day:20];
}

- (IBAction)go3Day:(id)sender
{
	[self goGregorianDate:2002 month:12 day:15];
}

- (IBAction)go3Night:(id)sender
{
	[self goGregorianDate:2003 month:12 day:10];
}
- (IBAction)go4Day:(id)sender
{
	[self goGregorianDate:2004 month:12 day:4];
}

- (IBAction)go4Night:(id)sender
{
	[self goGregorianDate:2005 month:11 day:29];
}
- (IBAction)go5Day:(id)sender
{
	[self goGregorianDate:2006 month:11 day:24];
}

- (IBAction)go5Night:(id)sender
{
	[self goGregorianDate:2007 month:11 day:19];
}
- (IBAction)go6Day:(id)sender
{
	[self goGregorianDate:2008 month:11 day:13];
}

- (IBAction)go6Night:(id)sender
{
	[self goGregorianDate:2009 month:11 day:8];
}

- (IBAction)go7Day:(id)sender
{
	[self goGregorianDate:2010 month:11 day:3];
}

- (IBAction)goAvatar1:(id)sender
{
	[self goGregorianDate:-33 month:12 day:25];
}

- (IBAction)goFallOfRome:(id)sender
{
	[self goGregorianDate:476 month:5 day:7];
}

- (IBAction)goMinoans:(id)sender
{
	[self goGregorianDate:-1536 month:8 day:23];
}

- (IBAction)goStonehenge:(id)sender
{
	[self goGregorianDate:-3100 month:6 day:4];
}

- (IBAction)goAlexander:(id)sender
{
	[self goGregorianDate:-353 month:6 day:3];
}

- (IBAction)goCaesar:(id)sender
{
//   13 July 100 BC Gaius Julius Caesar was born.,   NOTE: going with -98 because it is a warrior day on both
	[self goGregorianDate:-98 month:7 day:13];
}



- (IBAction)goMystery:(id)sender
{
	[[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"http://www.gaianmysteryschool.com/timesurfer"]];
}

- (void)checkForUpdates:(id)sender
{
	NSString *currVersionNumber = [[[NSBundle bundleForClass:[self class]]
		infoDictionary] objectForKey:@"CFBundleVersion"];
	
	NSDictionary *productVersionDict = [NSDictionary dictionaryWithContentsOfURL:
		[NSURL URLWithString:@"http://www.gaianmysteryschool.com/timesurfer/versionlist.xml"]];
	
	NSString *latestVersionNumber = [productVersionDict valueForKey:kAppName];
	
	if (latestVersionNumber)
	{
		if([latestVersionNumber isEqualTo: currVersionNumber])
		{
			NSRunAlertPanel(kAppName, @"This is the latest version", @"OK", nil, nil);
		}
		else
		{
			int button = NSRunAlertPanel(kAppName, [NSString stringWithFormat: @"There is a newer version (%@) availiable", latestVersionNumber], @"OK", @"Cancel", nil);
				
			if(NSOKButton == button)
			{
				[[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"http://www.gaianmysteryschool.com/timesurfer"]];
			}
		}
	}
}

- (IBAction)gotoBookmark:(id)sender
{
	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	NSArray *bookmarks=[defaults arrayForKey: kBookmarksKey];
	NSDictionary *dict=[defaults dictionaryForKey: [bookmarks objectAtIndex: [sender tag]]];
	[self goGregorianDate:[[dict objectForKey:kBookmarkYear] intValue] month:[[dict objectForKey:kBookmarkMonth] intValue] day:[[dict objectForKey:kBookmarkDay] intValue]];

}

- (IBAction)addBookmark:(id)sender
{
	[NSApp beginSheet: _bookmarksSavePanel modalForWindow: _window modalDelegate: self didEndSelector: nil contextInfo: nil];
}

- (IBAction)bookmarksSavePanelCancel:(id)sender
{
	[NSApp endSheet: _bookmarksSavePanel];
	[_bookmarksSavePanel orderOut: self];

}

- (IBAction)bookmarksSavePanelOK:(id)sender
{
	[NSApp endSheet: _bookmarksSavePanel];
	[_bookmarksSavePanel orderOut: self];

	[self saveBookmark:[_bookmarksSaveName stringValue]];

}

- (void)saveBookmark:(NSString *)title
{
	if (!title || ![title length]) return;
	
	NSMutableDictionary *dict=[[NSMutableDictionary alloc] init];
	
	[dict setObject:[_gregorianYear stringValue] forKey:kBookmarkYear];
	[dict setObject:[_gregorianDay stringValue] forKey:kBookmarkDay];
	[dict setObject:[NSString stringWithFormat:@"%d", [[_gregorianMonth selectedItem] tag]] forKey:kBookmarkMonth];

	// add title to list
	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	NSMutableArray *bookmarksMutable = [[NSMutableArray alloc] init];
	[bookmarksMutable addObjectsFromArray: [defaults arrayForKey: kBookmarksKey]];
	[bookmarksMutable addObject: title];

	[defaults setObject:bookmarksMutable forKey:kBookmarksKey];

	[defaults setObject:dict forKey:title];

	[defaults synchronize];
	
	[dict autorelease];
	[bookmarksMutable autorelease];
	
	[self updateBookmarksMenu];
	[_deleteBookmarkTableView noteNumberOfRowsChanged];	
}

- (void)updateBookmarksMenu
{
	int i, count = [_bookmarksMenu numberOfItems];

	for (i=0; i < count-3; i++)
		[_bookmarksMenu removeItemAtIndex: 3];

	NSArray *items = [[NSUserDefaults standardUserDefaults] arrayForKey: kBookmarksKey];
 
	count = [items count];
	
	for (i=0; i < count; i++)
	{
		NSString *name = [items objectAtIndex:i];
		NSMenuItem *item = [_bookmarksMenu addItemWithTitle:name action: @selector(gotoBookmark:) keyEquivalent:@""];

		[item setTag: i];

	}
}

- (void)tabView:(NSTabView *)tabView willSelectTabViewItem:(NSTabViewItem *)tabViewItem
{
	NSString *identifier=[tabViewItem identifier];
	
	if ([identifier compare: @"Notes"] == 0)
	{
		[self loadNotes];
	}
	else
	{
		[self saveNotes];
	}

}
- (NSString*)notesDirectory
{
	NSFileManager *manager = [NSFileManager defaultManager];
	NSString *notesDir = [NSHomeDirectory() stringByAppendingPathComponent: @"Documents/Time Surfer Notes/"];

	if (![manager fileExistsAtPath: notesDir])
		[manager createDirectoryAtPath: notesDir attributes:nil];


	return notesDir;
}

- (NSString*)longCountNotesFilename
{
	return  [[self notesDirectory] stringByAppendingPathComponent:[_tzolkin stringValue]];
}

- (NSString*)dreamspellNotesFilename
{

	return  [[self notesDirectory] stringByAppendingPathComponent:[_dreamspellGlyph stringValue]];
}

- (void)saveNotes
{
	NSString *lcNotes=[[_longCountNotes textStorage] string];
	if ([lcNotes length])
		[lcNotes writeToFile:_longCountNotesLastFilename atomically:NO];
	else
		[[NSFileManager defaultManager] removeFileAtPath: _longCountNotesLastFilename handler:nil];
		
	NSString *dsNotes=[[_dreamspellNotes textStorage] string];
	if ([dsNotes length])
		[dsNotes writeToFile:_dreamspellNotesLastFilename atomically:NO];
	else
		[[NSFileManager defaultManager] removeFileAtPath: _dreamspellNotesLastFilename handler:nil];
}

- (void)loadNotes
{
	[_longCountNotesToneSeal setStringValue: [_tzolkin stringValue]];
	[_longCountNotesLastFilename autorelease];
	_longCountNotesLastFilename=[[self longCountNotesFilename] copy];
	
	NSMutableAttributedString *attrString;
	NSFont *font = [NSFont systemFontOfSize:[NSFont smallSystemFontSize]];

	NSString *lcNotes=[NSString stringWithContentsOfFile: _longCountNotesLastFilename];
	if (!lcNotes) lcNotes=@"";
	attrString=[[NSMutableAttributedString alloc] initWithString:lcNotes];
	[attrString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, [attrString length])];
	[[_longCountNotes textStorage] setAttributedString: attrString];
	[attrString release];
	
	[_dreamspellNotesToneSeal setStringValue: [_dreamspellGlyph stringValue]];
	[_dreamspellNotesLastFilename autorelease];
	_dreamspellNotesLastFilename=[[self dreamspellNotesFilename] copy];
	NSString *dsNotes=[NSString stringWithContentsOfFile: _dreamspellNotesLastFilename];
	if (!dsNotes) dsNotes=@"";
	attrString=[[NSMutableAttributedString alloc] initWithString:dsNotes];
	[attrString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, [attrString length])];
	[[_dreamspellNotes textStorage] setAttributedString: attrString];
	[attrString release];
}

- (IBAction)longCountNotesInsertDate:(id)sender
{
	[_longCountNotes insertText:[NSString stringWithFormat:@"\n%d/%@/%@: ", [[_gregorianMonth selectedItem] tag], [_gregorianDay stringValue],  [_gregorianYear stringValue]]];
}

- (IBAction)dreamspellNotesInsertDate:(id)sender
{
	[_dreamspellNotes insertText:[NSString stringWithFormat:@"\n%d/%@/%@: ", [[_gregorianMonth selectedItem] tag], [_gregorianDay stringValue],  [_gregorianYear stringValue]]];
}

///******* delete bookmark


- (void)deleteBookmark:(id)sender
{
	[NSApp beginSheet: _deleteBookmarkPanel modalForWindow: _window modalDelegate: self didEndSelector: nil contextInfo: nil];
}

- (IBAction)deleteBookmarkButton:(id)sender
{
	id curRowNum;
	NSMutableArray *tmpList = [[NSMutableArray new] autorelease];

	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	NSArray *bookmarks=[defaults arrayForKey: kBookmarksKey];

	int i, count = [bookmarks count];
	
	for (i=0; i < count; i++)
	{
		NSEnumerator *selEnum = [_deleteBookmarkTableView selectedRowEnumerator];
		int found = NO;
		
		while ((curRowNum = [selEnum nextObject]) != nil) 
			if (i == [curRowNum intValue]) 
			{
				NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
				[defaults removeObjectForKey: [bookmarks objectAtIndex: i]];
				[defaults synchronize];
			
				found = YES;
				break;
			}
		
		if (!found)
		{
			[tmpList addObject: [bookmarks objectAtIndex: i]];
		}
	}
		
	if ([bookmarks count] != [tmpList count]) 
	{
		[defaults setObject:tmpList forKey:kBookmarksKey];
		[_deleteBookmarkTableView noteNumberOfRowsChanged];
		[_deleteBookmarkTableView deselectAll:nil];	}

	[self updateBookmarksMenu];
	[NSApp endSheet: _deleteBookmarkPanel];
	[_deleteBookmarkPanel orderOut: self];
	
}

- (IBAction)deleteBookmarkCancel:(id)sender
{
	[NSApp endSheet: _deleteBookmarkPanel];
	[_deleteBookmarkPanel orderOut: self];
}

- (int)numberOfRowsInTableView:(NSTableView *)tv
{
	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	return [[defaults arrayForKey: kBookmarksKey] count];
}

- (id)tableView:(NSTableView *)tv objectValueForTableColumn: (NSTableColumn *)tc row: (int)row
{
	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	return [[defaults arrayForKey: kBookmarksKey] objectAtIndex: row];
}

- (void)tableViewSelectionDidChange:(NSNotification *)notification
{
	BOOL state=NO;
	
	state = [_deleteBookmarkTableView numberOfSelectedRows];
	[_deleteBookmarkButton setEnabled: state];
}


- (IBAction)setEndDate:(id)sender
{
	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	NSDictionary *dict=[defaults dictionaryForKey: kEndDateKey];
	if (dict)
	{
		[_endDatePanelMonth selectItemAtIndex:[[dict objectForKey:kBookmarkMonth] intValue]-1];	
		[_endDatePanelDay setStringValue: [dict objectForKey:kBookmarkDay]];
		[_endDatePanelYear setStringValue: [dict objectForKey:kBookmarkYear]];
	}
	[NSApp beginSheet: _endDatePanel modalForWindow: _window modalDelegate: self didEndSelector: nil contextInfo: nil];


}

- (IBAction)endDatePanelOK:(id)sender
{
	NSMutableDictionary *dict=[[NSMutableDictionary alloc] init];
	
	[dict setObject:[_endDatePanelYear stringValue] forKey:kBookmarkYear];
	[dict setObject:[_endDatePanelDay stringValue] forKey:kBookmarkDay];
	[dict setObject:[NSString stringWithFormat:@"%d", [[_endDatePanelMonth selectedItem] tag]] forKey:kBookmarkMonth];

	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	[defaults setObject:dict forKey:kEndDateKey];

	[_yearStepper setMaxValue:[[TimeKit endDate] yearOfCommonEra]];
	[_yearStepper setMinValue:[[TimeKit startDate] yearOfCommonEra]];

	[NSApp endSheet: _endDatePanel];
	[_endDatePanel orderOut: self];
	[self calcGregorian:self];
}

- (IBAction)endDatePanelCancel:(id)sender
{
	[NSApp endSheet: _endDatePanel];
	[_endDatePanel orderOut: self];
}


- (IBAction)calendarBeginning:(id)sender
{
	[self gotoLongCount:0 katun:0 tun:0 uinal:0 kin:0];
}

- (IBAction)calendarEnding:(id)sender
{
	NSEvent *event=[NSApp currentEvent];
	if (([event modifierFlags] & NSAlternateKeyMask))
		[self setEndDate:sender];


	[self gotoLongCount:13 katun:0 tun:0 uinal:0 kin:0];
}

- (void)launchiCal:(NSString*)import
{
	if (import)
		[[NSWorkspace sharedWorkspace] openFile: import withApplication: @"iCal.app"];
}

- (IBAction)openiCal:(id)sender
{
	[[NSWorkspace sharedWorkspace] launchApplication: @"iCal.app"];
}

- (IBAction)exportLongCount:(id)sender
{
	int year,day, month;
	day=[_gregorianDay intValue]+1;
	month=[[_gregorianMonth selectedItem] tag];
	year=[_gregorianYear intValue];

	NSMutableString *export=[[NSMutableString alloc] init];
	NSFileManager *manager = [NSFileManager defaultManager];
	NSString *exportDir = [NSHomeDirectory() stringByAppendingPathComponent: @"Documents/"];

	if (![manager fileExistsAtPath: exportDir])
		[manager createDirectoryAtPath: exportDir attributes:nil];

	exportDir=[exportDir stringByAppendingPathComponent: [NSString stringWithFormat: @"%d Time Surfer Long Count.ics", year]];

	[export appendString: [NSString stringWithFormat: @"BEGIN:VCALENDAR\nVERSION:2.0\nX-WR-CALNAME:Time Surfer Long Count for %d\nPRODID:-//Gaian Mystery School//Time Surfer//EN\nCALSCALE:GREGORIAN\nMETHOD:PUBLISH\n", year]];	
	
	for (month=1; month<13; month++)
	{
		for (day=1; day<monthsMax[month]+1; day++)
		{
			TimeKit *tk = [[TimeKit alloc] init];
			
			[tk initDays: [tk longCountFromDate:month day:day year:year]];

			[export appendString: @"BEGIN:VEVENT\n"];
			[export appendString: [NSString stringWithFormat: @"DTSTART;VALUE=DATE:%d%02d%02d\n", year, month, day]];
			[export appendString: [NSString stringWithFormat: @"DTEND;VALUE=DATE:%d%02d%02d\n", year, month, day+1]];
			[export appendString: [NSString stringWithFormat: @"SUMMARY:%@\n",  [tk tzolkinSign]]];
			[export appendString: [NSString stringWithFormat: @"DESCRIPTION:Tzolkin: %@\\nHaab: %@\\nLong Count: %d.%d.%d.%d.%d\n", [tk tzolkinSign],  [tk haabSign], [tk baktun],[tk katun],[tk tun],[tk uinal],[tk kin]]];

			[export appendString: @"END:VEVENT\n"];

			[tk release];
		}
	}

	[export appendString: @"END:VCALENDAR\n"];
	[export writeToFile:exportDir atomically:NO];
	
	if (NSRunAlertPanel(kAppName, kiCalImport, @"Yes", @"No", nil))
		[self launchiCal: exportDir];
	
}

- (IBAction)exportDreamspell:(id)sender
{
	int year,day, month;
	day=[_gregorianDay intValue]+1;
	month=[[_gregorianMonth selectedItem] tag];
	year=[_gregorianYear intValue];

	NSMutableString *export=[[NSMutableString alloc] init];
	NSFileManager *manager = [NSFileManager defaultManager];
	NSString *exportDir = [NSHomeDirectory() stringByAppendingPathComponent: @"Documents/"];

	if (![manager fileExistsAtPath: exportDir])
		[manager createDirectoryAtPath: exportDir attributes:nil];

	exportDir=[exportDir stringByAppendingPathComponent: [NSString stringWithFormat: @"%d Time Surfer Dreamspell.ics", year]];

	[export appendString: [NSString stringWithFormat: @"BEGIN:VCALENDAR\nVERSION:2.0\nX-WR-CALNAME:Time Surfer Dreamspell for %d\nPRODID:-//Gaian Mystery School//Time Surfer//EN\nCALSCALE:GREGORIAN\nMETHOD:PUBLISH\n", year]];	
	
	for (month=1; month<13; month++)
	{
		for (day=1; day<monthsMax[month]+1; day++)
		{
			Dreamspell *ds = [[Dreamspell alloc] initWithDate:month day:day year:year];

			[export appendString: @"BEGIN:VEVENT\n"];
			[export appendString: [NSString stringWithFormat: @"DTSTART;VALUE=DATE:%d%02d%02d\n", year, month, day]];
			[export appendString: [NSString stringWithFormat: @"DTEND;VALUE=DATE:%d%02d%02d\n", year, month, day+1]];
			[export appendString: [NSString stringWithFormat: @"SUMMARY:%@\n",  [ds dreamspellGlyph]]];
			[export appendString: [NSString stringWithFormat: @"DESCRIPTION:%@\\n%@\\n%@",[ds dreamspellGlyph], [ds dreamspellTextExport], ([ds isGAP] ? @"(Galactic Activation Portal)" : @"")]];

			[export appendString: [NSString stringWithFormat: @"\\n\\n%@\\n%@", [ds moonDay], [ds dreamspellYearText]]];

			if ([ds isPacalAuspiciousDay])
			{
				[export appendString: @"\\n"];
				[export appendString: PACALDAY];
			}

			[export appendString: @"\nEND:VEVENT\n"];

			[ds release];
		}
	}

	[export appendString: @"END:VCALENDAR\n"];
	[export writeToFile:exportDir atomically:NO];
	
	if (NSRunAlertPanel(kAppName, kiCalImport, @"Yes", @"No", nil))
		[self launchiCal: exportDir];
	
}

@end
